package com.jinlejia.erp.ui.new_house.house;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfListRecyclerView;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.freedom.yefeng.yfrecyclerview.util.LogUtil;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.HouseTag;
import com.jinlejia.erp.bean.PropertyTypeBean;
import com.jinlejia.erp.common.WrapContentLinearLayoutManager;
import com.jinlejia.erp.databinding.FragmentNewHouseListBinding;
import com.jinlejia.erp.ui.common.CommonDialog;
import com.jinlejia.erp.ui.new_house.adapter.FilterSellPointAdapter;
import com.jinlejia.erp.ui.new_house.adapter.ListMapDropDownAdapter;
import com.jinlejia.erp.ui.new_house.adapter.NewHouseAdapter;
import com.jinlejia.erp.ui.new_house.adapter.RegionSelect1Adapter;
import com.jinlejia.erp.ui.new_house.adapter.RegionSelect2Adapter;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.LocationUtils;
import com.jinlejia.erp.utils.SharePTool;
import com.jinlejia.erp.utils.StringUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 * 新房列表
 */
public class NewHouseListFragment extends Fragment implements TextView.OnEditorActionListener,
        SwipeRefreshLayout.OnRefreshListener, YfLoadMoreListener {
    private View view;

    private ArrayList<Map<String, Object>> areaPopList = new ArrayList<>();
    private ArrayList<String> houseTagPopList = new ArrayList<>();
    private ArrayList<Map<String, Object>> area2Data = new ArrayList<>();
    private ArrayList<Map<String, Object>> priceTagPopList = new ArrayList<>();
    private ArrayList<Map<String, Object>> sortTagPopList = new ArrayList<>();
    private ArrayList<String> propertyTypeList = new ArrayList<>();//物业类型数据集合
    private String[] headers = {"区域", "卖点", "均价", "物业类型", "排序"};
    private RegionSelect1Adapter AreaMenuAdapter1;    //区域菜单
    private RegionSelect2Adapter AreaMenuAdapter2;    //区域菜单
    private FilterSellPointAdapter SellMenuAdapter;    //卖点菜单
    private FilterSellPointAdapter PropertyTypeAdapter;      //物业类型菜单
    private ListMapDropDownAdapter PriceMenuAdapter;    //均价菜单
    private ListMapDropDownAdapter SortMenuAdapter;    //排序菜单
    private List<View> popupViews = new ArrayList<>();
    private YfListRecyclerView oneRecycle;
    private YfListRecyclerView sellRecycler;
    private YfListRecyclerView propertyTypeRecycler;//物业类型Recycler
    private ListView sortView;
    private ListView priceView;
    private YfListRecyclerView twoRecycle;
    private String city = "", county = "", houseTag = "", keywords = "", orderBy = "0", averagePrice = "", propertyTypeString = "";
    private String minPrice = "", maxPrice = "", areaName = "";
    private int page = 1;

    NewHouseAdapter adapter;
    private CommonDialog dialog;
    LocationUtils locationUtils;
    private boolean mLoadingLock = false;

    public NewHouseListFragment() {
        // Required empty public constructor
    }

    private FragmentNewHouseListBinding binding;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_new_house_list, null);
            binding = DataBindingUtil.bind(view);
            binding.setEvent(this);
            initView();
        }
        // 缓存的rootView需要判断是否已经被加过parent，
        // 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        binding = DataBindingUtil.bind(view);
        binding.setEvent(this);
        return view;
    }

    private void initView() {

        //区域菜单  inflate(this,R.layout.item_area_layout,null)
        View AreaView = getLayoutInflater().inflate(R.layout.item_area_layout, null);
        oneRecycle = AreaView.findViewById(R.id.one_recycler_view);
        oneRecycle.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        twoRecycle = AreaView.findViewById(R.id.two_recycle_view);
        twoRecycle.setLayoutManager(new WrapContentLinearLayoutManager(getContext()));

        AreaMenuAdapter1 = new RegionSelect1Adapter(getActivity(), new ArrayList<>());
        AreaMenuAdapter2 = new RegionSelect2Adapter(getActivity(), new ArrayList<>());
        oneRecycle.setAdapter(AreaMenuAdapter1);
        twoRecycle.setAdapter(AreaMenuAdapter2);


        AreaMenuAdapter1.setOnItemSelectedListener(map -> {
            area2Data.clear();
            if (StringUtil.valueOf(map.get("countyName")).equals("区域")) {
                county = "";
                areaName = "";
                binding.dropDownMenu.setTabText("区域");
                AreaMenuAdapter2.changeMode(YfListMode.MODE_EMPTY);
                getData();
                binding.dropDownMenu.closeMenu();
            } else {
                area2Data = JSON.parseObject(StringUtil.valueOf(map.get("areaList")), new TypeReference<ArrayList<Map<String, Object>>>() {
                });
                if (area2Data.size() > 0) {
                    AreaMenuAdapter2.cur_position = -1;
                    AreaMenuAdapter2.setData(area2Data);
                    AreaMenuAdapter2.SelectorCounty(StringUtil.valueOf(map.get("countyName")));
                }
            }
        });

        AreaMenuAdapter1.setOnItemRemoveListener(map -> {
        });

        AreaMenuAdapter2.setOnItemSelectedListener((s, mCounty) -> {
            if (s.equals("全部")) {
                county = mCounty;
                areaName = "";
                binding.dropDownMenu.setTabText(mCounty);
            } else {
                areaName = s;
                county = "";
                binding.dropDownMenu.setTabText(s);
            }
            binding.dropDownMenu.closeMenu();
            page = 1;
            getData();
        });

        AreaMenuAdapter2.setOnItemRemoveListener(s -> {

        });

        //卖点菜单
        View SellingView = getLayoutInflater().inflate(R.layout.filter_more_layout, null);
        SellMenuAdapter = new FilterSellPointAdapter(houseTagPopList);
        sellRecycler = SellingView.findViewById(R.id.id_filter_more_list);
        sellRecycler.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        sellRecycler.setAdapter(SellMenuAdapter);
        TextView confirmBtn = SellingView.findViewById(R.id.id_confirm);

        confirmBtn.setOnClickListener(view -> {
            String tagStr = "";
            Iterator<String> it = SellMenuAdapter.s.iterator();
            while (it.hasNext()) {
                tagStr = tagStr.concat(",").concat(it.next());
            }
            houseTag = tagStr.replaceFirst(",", "");
            binding.dropDownMenu.closeMenu();
            page = 1;
            getData();
        });


        //region 物业类型菜单
        View PropertyTypeView = getLayoutInflater().inflate(R.layout.filter_unlimited_layout, null);
        PropertyTypeAdapter = new FilterSellPointAdapter(propertyTypeList);
        propertyTypeRecycler = (YfListRecyclerView) PropertyTypeView.findViewById(R.id.id_filter_unlimited_list);
        propertyTypeRecycler.setLayoutManager(new GridLayoutManager(getContext(), 3));
        propertyTypeRecycler.setAdapter(PropertyTypeAdapter);
        TextView OkBtn = (TextView) PropertyTypeView.findViewById(R.id.id_confirm);
        OkBtn.setOnClickListener(v -> {
            String tagStr = "";
            Iterator<String> it = PropertyTypeAdapter.s.iterator();
            while (it.hasNext()) {
                tagStr = tagStr.concat(",").concat(it.next());
            }
            propertyTypeString = tagStr.replaceFirst(",", "");
            binding.dropDownMenu.closeMenu();
            page = 1;
            getData();
        });


        //endregion

        //均价菜单
        final View priceAreaFooter = getLayoutInflater().inflate(R.layout.rent_price_area_footer, null);
        priceView = new ListView(getActivity());
        priceView.setDivider(getResources().getDrawable(R.drawable.shape_h_line));
        priceView.addFooterView(priceAreaFooter);


        //价格输入框
        final EditText leftPrice = priceAreaFooter.findViewById(R.id.et_left);
        final EditText rightPrice = priceAreaFooter.findViewById(R.id.et_right);
        //确定按钮
        TextView confirm = priceAreaFooter.findViewById(R.id.bt_confirm);
        priceView.setOnItemClickListener((adapterView, view, position, l) -> {
            PriceMenuAdapter.setCheckItem(position);
            binding.dropDownMenu.setTabText(position == 0 ? headers[2] : StringUtil.valueOf(priceTagPopList.get(position).get("name")));
            binding.dropDownMenu.closeMenu();
            averagePrice = StringUtil.valueOf(priceTagPopList.get(position).get("value"));
            page = 1;
            getData();
        });
        //确定按钮
        confirm.setOnClickListener(v -> {
            if (TextUtils.isEmpty(leftPrice.getText().toString())) {
                Toast.makeText(getActivity(), "请输入最低价格", Toast.LENGTH_SHORT).show();
            } else if (TextUtils.isEmpty(rightPrice.getText().toString())) {
                Toast.makeText(getActivity(), "请输入最高价格", Toast.LENGTH_SHORT).show();
            } else if (Integer.parseInt(rightPrice.getText().toString()) < Integer.parseInt(leftPrice.getText().toString())) {
                Toast.makeText(getActivity(), "最高价格必须大于最低价格", Toast.LENGTH_SHORT).show();
            } else {
                maxPrice = rightPrice.getText().toString();
                minPrice = leftPrice.getText().toString();
                averagePrice = minPrice + "," + maxPrice;
                binding.dropDownMenu.setTabText(minPrice + "-" + maxPrice);
                binding.dropDownMenu.closeMenu();
                page = 1;
                getData();
            }
        });
        //重置
        TextView btCancel = priceAreaFooter.findViewById(R.id.bt_cancel);
        btCancel.setOnClickListener(v -> {
            maxPrice = "";
            rightPrice.setText("");
            minPrice = "";
            leftPrice.setText("");
        });

        //排序菜单
        sortView = new ListView(getActivity());
        sortView.setDivider(getResources().getDrawable(R.drawable.shape_h_line));
        sortView.setOnItemClickListener((adapterView, view, position, l) -> {
            SortMenuAdapter.setCheckItem(position);
            orderBy = StringUtil.valueOf(sortTagPopList.get(position).get("value"));
            binding.dropDownMenu.setTabText(StringUtil.valueOf(sortTagPopList.get(position).get("name")));
            binding.dropDownMenu.setTabText(position == 0 ? headers[3] : StringUtil.valueOf(sortTagPopList.get(position).get("name")));
            binding.dropDownMenu.closeMenu();
            page = 1;
            getData();
        });

        // 添加到view List
        popupViews.add(AreaView);
        popupViews.add(SellingView);
        popupViews.add(priceView);
        popupViews.add(PropertyTypeView);
        popupViews.add(sortView);

        TextView contentView = new TextView(getActivity());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);
        //init dropdownview
        binding.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);

        binding.newHouseList.setHasFixedSize(true);
        binding.newHouseList.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        binding.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);

        binding.searchInput.setOnEditorActionListener(this);
        binding.refreshLayout.setOnRefreshListener(this);
        binding.newHouseList.enableAutoLoadMore(this);
        adapter = new NewHouseAdapter(new ArrayList<>());
        binding.newHouseList.setAdapter(adapter);
        adapter.changeMode(YfListMode.MODE_LOADING);

        adapter.setOnItemClickListener((view, o) -> {
            Map<String, Object> map = (Map<String, Object>) o;
            Intent intent = new Intent(getContext(), DetailNewHouseActivity.class);
            intent.putExtra("houseCode", StringUtil.valueOf(map.get("houseCode")));
            startActivity(intent);
        });

        city = SharePTool.getCity(getContext());
        requestLocation();
    }


    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                EventBus.getDefault().post("close", "TAG_FINISH_NEW_HOUSE");
                break;
            case R.id.location:
                Intent intent = new Intent(getActivity(), CitySelectActivity.class);
                startActivityForResult(intent, 100);
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
            if (!city.equals(data.getStringExtra("city"))) {
                city = data.getStringExtra("city");
                binding.location.setText(city);
                SharePTool.saveCity(getActivity(), city);
                getData();
                getSearchTag();
            }
        }
    }

    private void getSearchTag() {
        OkHttpUtils.get().url(ApiConfig.SEARCH_TAG_LIST)
                .addParams("city", city)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(getActivity(), response)) {

                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            //解析区域
                            if (data.containsKey("countryList")) {
                                areaPopList.clear();
                                JSONArray PriceTag = data.getJSONArray("countryList");
                                areaPopList = JSON.parseObject(PriceTag.toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                                });
                                AreaMenuAdapter1.setData(areaPopList);
                            }
                            //解析卖点
                            if (data.containsKey("houseTagList")) {
                                houseTagPopList.clear();
                                List<HouseTag> houseTagList;
                                JSONArray houseTag = data.getJSONArray("houseTagList");
                                houseTagList = JSON.parseObject(houseTag.toString(), new TypeReference<List<HouseTag>>() {
                                });
                                for (HouseTag h : houseTagList) {
                                    houseTagPopList.add(h.getName());
                                }
                                SellMenuAdapter.setData(houseTagPopList);
                                SellMenuAdapter.notifyDataSetChanged();
                            }
                            //解析物业类型
                            if (data.containsKey("typePropertiesList")) {
                                propertyTypeList.clear();
                                List<PropertyTypeBean> propertyList = new ArrayList<>();
                               JSONArray typeProper = data.getJSONArray("typePropertiesList");
                                propertyList = JSON.parseObject(typeProper.toString(), new TypeReference<List<PropertyTypeBean>>() {
                                });
                                for (PropertyTypeBean propertyTypeBean : propertyList) {
                                    propertyTypeList.add(propertyTypeBean.getName());
                                }
                                PropertyTypeAdapter.setData(propertyTypeList);
                                PropertyTypeAdapter.notifyDataSetChanged();
                            }
                            //解析均价
                            if (data.containsKey("averagePriceList")) {
                                priceTagPopList.clear();
                                JSONArray PriceTag = data.getJSONArray("averagePriceList");
                                priceTagPopList = JSON.parseObject(PriceTag.toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                                });
                                PriceMenuAdapter = new ListMapDropDownAdapter(getActivity(), priceTagPopList);
                                priceView.setAdapter(PriceMenuAdapter);
                            }
                            //解析排序
                            if (data.containsKey("orderTagList")) {
                                JSONArray PriceTag = data.getJSONArray("orderTagList");
                                sortTagPopList = JSON.parseObject(PriceTag.toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                                });
                                SortMenuAdapter = new ListMapDropDownAdapter(getActivity(), sortTagPopList);
                                sortView.setAdapter(SortMenuAdapter);
                            }
                        }
                    }
                });
    }

    private void getData() {

        OkHttpUtils.get().url(ApiConfig.NEWHOUSE_LIST)
                .addParams("pageIndex", String.valueOf(page))
                .addParams("pageSize", "20")
                .addParams("city", city)
                .addParams("county", county)
                .addParams("latitude", SharePTool.getLatitude(getContext()) + "")
                .addParams("longitude", SharePTool.getLongitude(getContext()) + "")
                .addParams("houseTag", houseTag)
                .addParams("keywords", keywords)
                .addParams("averagePriceStr", averagePrice)
                .addParams("areaName", areaName)
                .addParams("orderBy", orderBy)
                .addParams("propertType",propertyTypeString)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(getActivity(), response, adapter)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            if (data.containsKey("page")) {
                                JSONArray jsonArray = data.getJSONArray("page");
                                ArrayList<Map<String, Object>> infoList = JSON.parseObject(jsonArray.toJSONString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                                });
                                if (page == 1) {
                                    adapter.setData(infoList);
                                } else {
                                    adapter.addData(infoList);
                                }
                                mLoadingLock = false;
                                if (binding.refreshLayout.isRefreshing()) {
                                    binding.refreshLayout.setRefreshing(false);
                                }
                            }
                        }
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onRefresh() {
        page = 1;
        getData();
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            //搜索
            Log.e("onEditorAction", "搜索 " + binding.searchInput.getText().toString());
            page = 1;
            keywords = binding.searchInput.getText().toString();
            getData();

        }
        return true;
    }

    @Override
    public void loadMore() {
        if (mLoadingLock) {
            return;
        }
        mLoadingLock = true;
        page++;
        getData();
    }

    private void requestLocation() {
        locationUtils = new LocationUtils(getActivity(), LocationUtils.DIALOG_GTYPE_SETTING);
        //设置自己需要定位的参数
        locationUtils.getLocationClientOption().setScanSpan(1000);
        //设置权限
        locationUtils.setPermition();
        //开始定位
        locationUtils.startLocation();

        //监听定位返回的数据
        locationUtils.getLocationListener(location -> {
            if (getContext() == null) return;
            if (getActivity() == null) return;
            city = location.getCity();
            SharePTool.saveLocation(getContext(), 117.192294, 39.092751, "天津市", "");
            if (location.getCity() == null) {
                SharePTool.saveLocation(getContext(), 117.192294, 39.092751, "天津市", "");
            } else if (location.getCity().equals("天津市")) {
                SharePTool.saveLocation(getActivity(), location.getLongitude(), location.getLatitude(), location.getCity(), location.getDistrict());
            } else {
                dialog = new CommonDialog(getContext(), "城市切换", "您当前定位的城市为" + location.getCity() + ",是否切换的该城市?", "切换", "取消");
                dialog.show();
                dialog.setConfirmListener(new CommonDialog.OnConfirmListener() {
                    @Override
                    public void confirm() {
                        if (getActivity() == null) return;
                        binding.location.setText(location.getCity());
                        SharePTool.saveLocation(getActivity(), location.getLongitude(), location.getLatitude(), location.getCity(), location.getDistrict());
                    }
                });

            }
            getData();
            getSearchTag();
            locationUtils.stopLocation();
        });
    }

    /**
     * 地图定位权限返回
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        locationUtils.onLocationRequestPermissionsResult(requestCode, permissions, grantResults);
    }


}
